'use strict';
const db = uniCloud.database();
exports.main = async (event, context) => {
	if(event.type == 0){
	//type =0,获取用户地址
		let res = await obtain_address(event)
		return res
	}else if(event.type == 1){
	//type =1,修改用户地址
		let res = await edit_address(event)
		return res
	}else if(event.type == 2){
	//type =2,添加用户地址
		let res = await addto_address(event)
		return res
	}else if(event.type == 3){
	//type =3,删除用户地址
		let res = await remove_address(event)
		return res
	}
	
	
};

//获取用户地址
const obtain_address = async (event) => {
	const addressDetail = db.collection('address');
	let res =await addressDetail.where({user_id: event._id}).get();
	return res
}

//修改用户地址
const edit_address = async (event) => {
	const address = db.collection('address');
	let address_id = event._id;
	let res = await address.where({_id: address_id}).count();
	if(res.total){
		if(event.default == 1){
			address.where({user_id: event.user_id,default:1}).update({default:0});
			delete event._id
			res = await address.where({_id: address_id}).update(event);
			return res
		}else {
			delete event._id
			res = await address.where({_id: address_id}).update(event);
			return res
		}
	}else {
		return res
	}
}

//添加用户地址
const addto_address = async (event) => {
	const address = db.collection('address');
	if(event.default == 1){
		let res = await address.where({user_id: event.user_id,default: 1}).update({default: 0});
		if(res){
			let res1 = await address.add(event);
			return res1
		}else {
			return res
		}
	}else {
		let res = await address.add(event);
		return res
	}
}

//删除用户地址
const remove_address = async (event) => {
	const address = db.collection('address');
	let res =await address.where({_id: event._id}).count();
	if(res.total == 1){
		res =await address.where({_id: event._id}).remove();
		return res
	}else {
		return res
	}
}